package com.imooc.sc.dao.impl;

import com.imooc.sc.dao.CourseDao;
import com.imooc.sc.entity.Course;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author wangc
 */

@Repository
public class CourseDaoImpl implements CourseDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void insert(Course course) {
        String sql = "insert into course(name, score) values(?,?,?)";
        jdbcTemplate.update(sql, course.getName(), course.getScore());
    }

    @Override
    public void update(Course course) {
        String sql = "update course set name=?,score=? where id=?";
        jdbcTemplate.update(sql, course.getName(), course.getId(), course.getScore());
    }

    @Override
    public void delete(int id) {
        String sql = "delete from course where id=?";
        jdbcTemplate.update(sql, id);
    }

    @Override
    public Course selete(int id) {
        String sql = "delete * from course where id=?";
        return jdbcTemplate.queryForObject(sql, new CourseRowMapper(),id);
    }

    @Override
    public List<Course> selectAll() {
        String sql = "select * from course where id=?";
        return jdbcTemplate.query(sql, new CourseDaoImpl.CourseRowMapper());
    }

    private class CourseRowMapper implements RowMapper<Course> {

        @Override
        public Course mapRow(ResultSet resultSet, int i) throws SQLException {
            Course course = new Course();
            course.setId(resultSet.getInt("id"));
            course.setName(resultSet.getString("name"));
            course.setScore(resultSet.getInt("name"));
            return course;
        }
    }
}
